<template>
  <div class="equipment-table">
    <!-- 顶部导航栏 -->
    <!-- <header class="nav-bar">
      <button class="nav-tab selected">工艺流程图</button>
      <button class="nav-tab">监控中心</button>
      <button class="nav-tab">设备列表</button>
    </header>   -->

    <!-- 搜索 & 功能按钮 -->
    <div>
    <!-- 搜索栏与操作按钮 -->
    <el-form :inline="true" class="search-container">
      <el-form-item>
        <el-input
          v-model="searchQuery"
          placeholder="编号/名称/地点"
          @input="onSearch"
          class="search-input"
          clearable
          prefix-icon="el-icon-search"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="openAddDeviceModal">添加设备</el-button>
        <el-button>导入台账</el-button>
        <el-button>生成二维码</el-button>
        <el-button type="danger">删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="data" style="width: 100%" border>
      <el-table-column type="index" label="#" width="50" />
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column prop="deviceCode" label="设备编号" width="120" />
      <el-table-column prop="deviceName" label="设备名称" width="180" />
      <el-table-column prop="deviceType" label="设备型号" width="140" />
      <el-table-column label="设备图片" width="140">
        <template #default>
          <span>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="deviceLocation" label="设备地点" />
      <el-table-column prop="deviceStatus" label="设备状态" width="100" />
      <!-- <el-table-column prop="responsible" label="责任人" width="120" />   -->
      <!-- <el-table-column prop="comment" label="补充备注" />   -->
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            @click="onMonitor(scope.row)"
            >监测</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="onViewDetails(scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="onControl(scope.row)"
            >监控</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="onSettings(scope.row)"
            >点检设置</el-button
          >
          <el-button
            size="mini"
            type="text"
            class="danger-text"
            @click="onDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="formData.pageNum"
        :limit.sync="formData.pageSize"
        @pagination="getList"
      />
  </div>



   <el-dialog
    title="添加设备"
    :visible.sync="showAddDeviceModal"
    width="80%"
    @close="closeAddDeviceModal"
   >
      <el-form
        :model="formData"
        ref="deviceForm"
        label-width="120px"
        class="device-form"
      >
        <!-- 第一行：左侧和右侧表单布局 -->
        <div class="form-row">
          <el-form-item label="设备编号 *" prop="deviceCode">
            <el-input v-model="formData.deviceCode" placeholder="请输入设备编号" />
          </el-form-item>
          <el-form-item label="生产厂家">
            <el-input v-model="formData.manufacturer" placeholder="请输入生产厂家" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="设备名称 *" prop="deviceName">
            <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="formData.supplier" placeholder="请输入供应商" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="设备型号">
            <el-input v-model="formData.deviceType" placeholder="请输入设备型号" />
          </el-form-item>
          <el-form-item label="保养周期">
            <el-input v-model="formData.warranty" placeholder="请输入保养周期" />
          </el-form-item>
        </div>


        <!-- 上传图片 -->
        <div class="form-row">
          <el-form-item label="上传图片">
             <el-upload
              class="upload-demo"
              multiple
              :file-list="fileList"
              :on-remove="(file) => handleFileRemove(file, 'sample')"
              :action="uploadUrlPreparation"
              :before-upload="beforeFileUpload"
              :on-success="(response, file) => handleFileSuccess(response, file, 'sample')"
              :headers="headers"
              :data="{ deviceCode: formData.deviceCode}"
              list-type="text"
              accept="image/*"
             >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="技术文档">
            <el-button>点击上传</el-button>
          </el-form-item>
        </div>

        <!-- 第二部分 -->
        <div class="form-row">
          <el-form-item label="设备地点 *" prop="deviceLocation">
            <el-input v-model="formData.deviceLocation" placeholder="请输入设备地点" />
          </el-form-item>
          <el-form-item label="出厂日期">
            <el-date-picker
              v-model="formData.factoryDate"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="设备状态">
            <el-select v-model="formData.deviceStatus" placeholder="请选择">
              <el-option label="已启用" value="已启用" />
              <el-option label="未启用" value="未启用" />
            </el-select>
          </el-form-item>
          <el-form-item label="投用日期">
            <el-date-picker
              v-model="formData.useDate"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="责任部门">
            <el-select v-model="formData.department" placeholder="请选择">
              <el-option label="部门1" value="部门1" />
              <el-option label="部门2" value="部门2" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="责任人">
            <el-select v-model="formData.responsiblePerson" placeholder="请选择">
              <el-option label="张三" value="张三" />
              <el-option label="李四" value="李四" />
            </el-select>
          </el-form-item>

        </div>

        <div class="form-row">
          <el-form-item label="设备类别">
            <el-select v-model="formData.deviceCategory" placeholder="请选择">
              <el-option label="类别1" value="类别1" />
              <el-option label="类别2" value="类别2" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属站点">
            <el-select v-model="formData.site" placeholder="请选择">
              <el-option label="站点1" value="站点1" />
              <el-option label="站点2" value="站点2" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

    <!-- 弹窗底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeAddDeviceModal">取消</el-button>
      <el-button type="primary" @click="onSubmitDevice">确定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import {addSevice,list} from "@/api/wushui/site";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      // 上传相关
      uploadUrlPreparation: process.env.VUE_APP_BASE_API + "/api/common/uploadPreparation",
      fileList: [], // 采样准备文件
      headers: {
        Authorization: "Bearer " + getToken(), // 如果需要认证
      },
      deviceCode : null ,

      total: 0,

      showAddDeviceModal: false, // 控制弹窗显示
      formData: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: "",
        deviceName: "",
        deviceType: "",
        manufacturer: "",
        supplier: "",
        warranty: "",
        deviceLocation: "",
        deviceStatus: "",
        factoryDate: "",
        useDate:""

      },
      searchQuery: "",
      currentPage: 1,
      pageSize: 5, // 每页5条
      data: [],
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(
        this.data.filter(
          (item) =>
            item.code.includes(this.searchQuery) ||
            item.name.includes(this.searchQuery) ||
            item.location.includes(this.searchQuery)
        ).length / this.pageSize
      );
    },
  },
  created() {
    this.getList();
  },

  methods: {

     // 文件上传成功
    handleFileSuccess(response, file, type) {
      this.getList();
      this.fileList.push(file);
    },

    // 文件上传前验证
     beforeFileUpload(file) {
      // 上传前验证逻辑，例如检查文件类型和重复文件
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只允许上传图片文件');
        return false;
      }

      // 检查文件名是否已经存在
      const exists = this.fileList.some(f => f.name === file.name);
      if (exists) {
        this.$message.error('文件名称重复');
        return false;
      }
      const deviceCode = this.formData.deviceCode;
      if (deviceCode==""){
        this.$message.error('请填写设备编号');
        return false;
      }
      if(this.fileList.length >= 1){
        this.$message.error('只允许上传一张图片');
        return false;
      }


      return true; // 验证通过，可以上传
    },


     // 删除文件
    handleFileRemove(file) {
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
    },
     // 获取列表数据
    getList() {
      this.loading = true;
      list(this.formData).then(response => {
        this.data = response.rows;
        console.log(response)
        this.total = response.total;
        this.loading = false;
      });
    },
    openAddDeviceModal() {
      this.showAddDeviceModal = true;
    },
    closeAddDeviceModal() {
      this.resetFormData();
      this.showAddDeviceModal = false;
    },
    resetFormData() {
      this.formData = {
        deviceCode: "",
        deviceName: "",
        deviceType: "",
        manufacturer: "",
        supplier: "",
        warranty: "",
        deviceLocation: "",
        deviceStatus: "",
      };
    },
    onSubmitDevice() {
      if (!this.formData.deviceCode || !this.formData.deviceName || !this.formData.deviceLocation) {
        alert("请填写带 * 的必填项");
        return;
      }

        addSevice(this.formData).then((response) => {
          this.getList();
          console.log('response:', response);
          this.closeAddDeviceModal();
          alert(`设备已成功添加`);
        }).catch(() => {
          this.$message.error("获取数据失败");
        });
    },
    onUploadImage(event) {
      const file = event.target.files[0];
      if (file) {
        alert(`图片已上传：${file.name}`);
      }
    },
    onSearch() {
      this.currentPage = 1;
    },
    prevPage() {
      if (this.currentPage > 1) this.currentPage--;
    },
    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++;
    },
    onMonitor(item) {
      alert(`监测设备：${item.name}`);
    },
    onViewDetails(item) {
      alert(`查看设备详情：${item.name}`);
    },
    onControl(item) {
      alert(`监控设备：${item.name}`);
    },
    onSettings(item) {
      alert(`设备点检设置：${item.name}`);
    },
    onDelete(item) {
      if (confirm(`确定删除设备：${item.name}？`)) {
        this.data = this.data.filter((i) => i !== item);
      }
    },
  },
};
</script>

<style scoped>

/* 表单样式优化 */
.device-form {
  margin: 20px 0;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row > .el-form-item {
  flex: 1; /* 平分宽度 */
}

.upload-demo .el-icon-plus {
  font-size: 24px;
  color: #aaa;
}
/* 页面整体样式 */
.equipment-table {
  font-family: Arial, sans-serif;
  padding: 20px;
  background-color: #f9f9f9;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  justify-content: flex-start;
  background-color: #007bff;
  color: white;
  padding: 10px;
}
.nav-tab {
  margin-right: 15px;
  padding: 8px 15px;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 14px;
  background: none;
}
.nav-tab.selected {
  border-bottom: 2px solid white;
  font-weight: bold;
}

/* 搜索和操作按钮 */
.search-container {
  display: flex;
  margin: 15px 0;
  align-items: center;
}
.search-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}
.action-button,
.delete-button {
  margin-left: 10px;
  background-color: #007bff;
  color: white;
  padding: 8px 10px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}
.delete-button {
  background-color: #dc3545;
}

/* 表格样式 */
.table-container {
  background: white;
  border-radius: 4px;
  overflow-x: auto;
}
table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
  font-size: 14px;
}
table th,
table td {
  padding: 10px;
  border: 1px solid #e5e5e5;
}
thead th {
  background-color: #007bff;
  color: white;
  font-weight: bold;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}
button[disabled] {
  background: #ccc;
  cursor: not-allowed;
}
.operation {
  color: #007bff;
  cursor: pointer;
}
.operation:hover {
  text-decoration: underline;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.modal-content {
  background: white;
  width: 60%;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.modal-header h3 {
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.modal-body {
  margin-top: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.form-grid div {
  display: flex;
  flex-direction: column;
}

.modal-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.cancel-button,
.submit-button {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.cancel-button {
  background: #ccc;
  color: #333;
}

.submit-button {
  background: #007bff;
  color: white;
}
</style>
